﻿using Modbus.Device;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO.Ports;
using System.Windows.Forms;

namespace 水库上位机
{
    // 圆角面板控件
    public class UPanel : Panel
    {
        private int cornerRadius = 10;

        public int CornerRadius 
        {
            get { return cornerRadius; }
            set 
            {
                cornerRadius = value;
                this.Invalidate();
            }
        }

        private Color borderColor = Color.Black;

        public Color BorderColor
        {
            get { return borderColor; }
            set 
            {
                borderColor = value;
                this.Invalidate();
            }
        }

        private int borderWidth = 1;

        public int BorderWidth
        {
            get { return borderWidth; }
            set 
            {
                borderWidth = value;
                this.Invalidate();
            }
        }

        public UPanel()
        {
            this.DoubleBuffered = true;
            this.ResizeRedraw = true;
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            Graphics g = e.Graphics;
            g.SmoothingMode = SmoothingMode.AntiAlias;

            // 创建圆角矩形路径
            Rectangle rect = new Rectangle(0, 0, this.Width - 1, this.Height - 1);
            GraphicsPath path = GetRoundRectangle(rect, cornerRadius);

            // 填充背景
            using (Brush brush = new SolidBrush(this.BackColor))
            {
                g.FillPath(brush, path);
            }

            // 绘制边框
            using (Pen pen = new Pen(borderColor, borderWidth))
            {
                g.DrawPath(pen, path);
            }
        }

        private GraphicsPath GetRoundRectangle(Rectangle rect, int radius)
        {
            GraphicsPath path = new GraphicsPath();
            int diameter = radius * 2;

            // 左上圆角
            path.AddArc(rect.X, rect.Y, diameter, diameter, 180, 90);
            // 右上圆角
            path.AddArc(rect.Right - diameter, rect.Y, diameter, diameter, 270, 90);
            // 右下圆角
            path.AddArc(rect.Right - diameter, rect.Bottom - diameter, diameter, diameter, 0, 90);
            // 左下圆角
            path.AddArc(rect.X, rect.Bottom - diameter, diameter, diameter, 90, 90);
            path.CloseFigure();

            return path;
        }
    }

    // 指示灯控件
    public class ULightControl : Panel
    {
        private Color onColor = Color.Green;
        private Color offColor = Color.Red;
        private bool isOn = false;

        public Color OnColor
        {
            get { return onColor; }
            set { onColor = value; Invalidate(); }
        }

        public Color OffColor
        {
            get { return offColor; }
            set { offColor = value; Invalidate(); }
        }

        public bool IsOn
        {
            get { return isOn; }
            set 
            {
                isOn = value;
                this.BackColor = isOn ? onColor : offColor;
                Invalidate();
            }
        }

        public ULightControl()
        {
            this.DoubleBuffered = true;
            this.ResizeRedraw = true;
            this.Size = new Size(20, 20);
            this.BackColor = offColor;
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            Graphics g = e.Graphics;
            g.SmoothingMode = SmoothingMode.AntiAlias;

            // 绘制圆形指示灯
            using (Brush brush = new SolidBrush(this.BackColor))
            {
                g.FillEllipse(brush, new Rectangle(1, 1, this.Width - 2, this.Height - 2));
            }
            using (Pen pen = new Pen(Color.Black, 1))
            {
                g.DrawEllipse(pen, new Rectangle(1, 1, this.Width - 2, this.Height - 2));
            }

            // 添加高光效果
            if (isOn)
            {
                using (Brush brush = new SolidBrush(Color.FromArgb(100, Color.White)))
                {
                    g.FillEllipse(brush, new Rectangle(3, 3, this.Width - 6, this.Height - 6));
                }
            }
        }
    }

    // 参数信息框控件
    public class ParamTextBox : Panel
    {
        private Label titleLabel = new Label();
        private Label valueLabel = new Label();

        public string Title
        {
            get { return titleLabel.Text; }
            set { titleLabel.Text = value; }
        }

        public string Value
        {
            get { return valueLabel.Text; }
            set { valueLabel.Text = value; }
        }

        public ParamTextBox()
        {
            this.DoubleBuffered = true;
            this.ResizeRedraw = true;
            this.BackColor = Color.White;
            this.BorderStyle = BorderStyle.FixedSingle;

            titleLabel.Font = new Font("微软雅黑", 9F, FontStyle.Regular);
            titleLabel.ForeColor = Color.Black;
            titleLabel.AutoSize = true;
            titleLabel.Location = new Point(5, 5);

            valueLabel.Font = new Font("微软雅黑", 9F, FontStyle.Bold);
            valueLabel.ForeColor = Color.Blue;
            valueLabel.AutoSize = true;
            valueLabel.Location = new Point(5, 25);

            this.Controls.Add(titleLabel);
            this.Controls.Add(valueLabel);
        }
    }

    // 仪表控件
    public class UInstrumentControl : Panel
    {
        private double value = 0;
        private double maxValue = 300;
        private string unit = "V";

        public double Value
        {
            get { return value; }
            set 
            {
                this.value = value;
                this.Invalidate();
            }
        }

        public double MaxValue
        {
            get { return maxValue; }
            set 
            {
                maxValue = value;
                this.Invalidate();
            }
        }

        public string Unit
        {
            get { return unit; }
            set 
            {
                unit = value;
                this.Invalidate();
            }
        }

        public UInstrumentControl()
        {
            this.DoubleBuffered = true;
            this.ResizeRedraw = true;
            this.Size = new Size(100, 100);
            this.BackColor = Color.White;
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            Graphics g = e.Graphics;
            g.SmoothingMode = SmoothingMode.AntiAlias;

            int centerX = this.Width / 2;
            int centerY = this.Height / 2;
            int radius = Math.Min(centerX, centerY) - 10;

            // 绘制表盘背景
            using (Brush brush = new SolidBrush(Color.LightGray))
            {
                g.FillEllipse(brush, centerX - radius, centerY - radius, radius * 2, radius * 2);
            }

            // 绘制表盘外圈
            using (Pen pen = new Pen(Color.Black, 2))
            {
                g.DrawEllipse(pen, centerX - radius, centerY - radius, radius * 2, radius * 2);
            }

            // 绘制刻度
            using (Pen pen = new Pen(Color.Black, 1))
            {
                for (int i = 0; i <= 12; i++)
                {
                    double angle = Math.PI * 1.5 - (Math.PI * 1.2) * i / 12;
                    int x1 = centerX + (int)(Math.Cos(angle) * radius * 0.8);
                    int y1 = centerY - (int)(Math.Sin(angle) * radius * 0.8);
                    int x2 = centerX + (int)(Math.Cos(angle) * radius);
                    int y2 = centerY - (int)(Math.Sin(angle) * radius);
                    g.DrawLine(pen, x1, y1, x2, y2);
                }
            }

            // 绘制刻度值
            using (Font font = new Font("Arial", 7F, FontStyle.Regular))
            {
                using (Brush brush = new SolidBrush(Color.Black))
                {
                    string[] values = { "0", "30", "60", "90", "120", "150", "180", "210", "240", "270", "300" };
                    for (int i = 0; i < values.Length; i++)
                    {
                        double angle = Math.PI * 1.5 - (Math.PI * 1.2) * i / 10;
                        int x = centerX + (int)(Math.Cos(angle) * radius * 1.2);
                        int y = centerY - (int)(Math.Sin(angle) * radius * 1.2);
                        SizeF size = g.MeasureString(values[i], font);
                        g.DrawString(values[i], font, brush, x - size.Width / 2, y - size.Height / 2);
                    }
                }
            }

            // 绘制单位
            using (Font font = new Font("微软雅黑", 9F, FontStyle.Bold))
            {
                using (Brush brush = new SolidBrush(Color.Blue))
                {
                    g.DrawString(unit, font, brush, centerX - 5, centerY - 40);
                }
            }

            // 绘制指针
            using (Pen pen = new Pen(Color.Red, 2))
            {
                double valueRatio = Math.Min(value / maxValue, 1.0);
                double angle = Math.PI * 1.5 - (Math.PI * 1.2) * valueRatio;
                int x = centerX + (int)(Math.Cos(angle) * radius * 0.6);
                int y = centerY - (int)(Math.Sin(angle) * radius * 0.6);
                g.DrawLine(pen, centerX, centerY, x, y);
            }

            // 绘制中心点
            using (Brush brush = new SolidBrush(Color.Black))
            {
                g.FillEllipse(brush, centerX - 3, centerY - 3, 6, 6);
            }
        }
    }

    // 水池控件
    public class WaterTankControl : Panel
    {
        private double waterLevel = 0.0;
        private double maxWaterLevel = 100.0;
        private string tankName = "水池";

        public double WaterLevel
        {
            get { return waterLevel; }
            set 
            {
                waterLevel = value;
                this.Invalidate();
            }
        }

        public double MaxWaterLevel
        {
            get { return maxWaterLevel; }
            set 
            {
                maxWaterLevel = value;
                this.Invalidate();
            }
        }

        public string TankName
        {
            get { return tankName; }
            set 
            {
                tankName = value;
                this.Invalidate();
            }
        }

        public WaterTankControl()
        {
            this.DoubleBuffered = true;
            this.ResizeRedraw = true;
            this.Size = new Size(150, 150);
            this.BackColor = Color.White;
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            Graphics g = e.Graphics;
            g.SmoothingMode = SmoothingMode.AntiAlias;

            // 绘制池体
            Rectangle tankRect = new Rectangle(10, 10, this.Width - 20, this.Height - 30);
            using (Pen pen = new Pen(Color.Black, 2))
            {
                g.DrawRectangle(pen, tankRect);
            }

            // 绘制水
            double waterRatio = Math.Min(waterLevel / maxWaterLevel, 1.0);
            int waterHeight = (int)(tankRect.Height * waterRatio);
            using (Brush brush = new LinearGradientBrush(
                new Point(tankRect.Left, tankRect.Bottom - waterHeight),
                new Point(tankRect.Right, tankRect.Bottom),
                Color.LightBlue, Color.Blue))
            {
                g.FillRectangle(brush, tankRect.Left + 1, tankRect.Bottom - waterHeight, 
                    tankRect.Width - 1, waterHeight);
            }

            // 绘制水池名称
            using (Font font = new Font("微软雅黑", 9F, FontStyle.Bold))
            {
                using (Brush brush = new SolidBrush(Color.Black))
                {
                    SizeF textSize = g.MeasureString(tankName, font);
                    g.DrawString(tankName, font, brush, 
                        tankRect.Left + (tankRect.Width - textSize.Width) / 2, 
                        tankRect.Bottom + 5);
                }
            }
        }
    }

    // 报警灯控件
    public class AlarmControl : Panel
    {
        private bool isAlarmOn = false;
        private Color alarmColor = Color.Red;

        public bool IsAlarmOn
        {
            get { return isAlarmOn; }
            set 
            {
                isAlarmOn = value;
                this.Invalidate();
            }
        }

        public Color AlarmColor
        {
            get { return alarmColor; }
            set 
            {
                alarmColor = value;
                this.Invalidate();
            }
        }

        public AlarmControl()
        {
            this.DoubleBuffered = true;
            this.ResizeRedraw = true;
            this.Size = new Size(30, 30);
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            Graphics g = e.Graphics;
            g.SmoothingMode = SmoothingMode.AntiAlias;

            // 绘制底座
            using (Brush brush = new SolidBrush(Color.Gray))
            {
                g.FillRectangle(brush, new Rectangle(10, 20, 10, 10));
            }

            // 绘制报警灯
            if (isAlarmOn)
            {
                // 闪烁效果
                using (Brush brush = new SolidBrush(alarmColor))
                {
                    g.FillEllipse(brush, new Rectangle(5, 5, 20, 15));
                }
                // 高光
                using (Brush brush = new SolidBrush(Color.FromArgb(100, Color.White)))
                {
                    g.FillEllipse(brush, new Rectangle(7, 7, 10, 7));
                }
            }
            else
            {
                using (Brush brush = new SolidBrush(Color.Gray))
                {
                    g.FillEllipse(brush, new Rectangle(5, 5, 20, 15));
                }
            }
            
            using (Pen pen = new Pen(Color.Black, 1))
            {
                g.DrawEllipse(pen, new Rectangle(5, 5, 20, 15));
            }
        }
    }

    // 水泵控件
    public class WaterPumpControl : Panel
    {
        private bool isRunning = false;
        private string pumpName = "抽水泵";

        public bool IsRunning
        {
            get { return isRunning; }
            set 
            {
                isRunning = value;
                this.Invalidate();
            }
        }

        public string PumpName
        {
            get { return pumpName; }
            set 
            {
                pumpName = value;
                this.Invalidate();
            }
        }

        public WaterPumpControl()
        {
            this.DoubleBuffered = true;
            this.ResizeRedraw = true;
            this.Size = new Size(150, 80);
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            Graphics g = e.Graphics;
            g.SmoothingMode = SmoothingMode.AntiAlias;

            // 绘制泵体
            Rectangle pumpRect = new Rectangle(10, 10, this.Width - 20, this.Height - 20);
            using (Brush brush = new SolidBrush(isRunning ? Color.LightGray : Color.Gray))
            {
                g.FillRectangle(brush, pumpRect);
            }
            using (Pen pen = new Pen(Color.Black, 2))
            {
                g.DrawRectangle(pen, pumpRect);
            }

            // 绘制泵标志
            using (Pen pen = new Pen(isRunning ? Color.Blue : Color.DarkGray, 3))
            {
                // 绘制泵的简单示意图
                g.DrawEllipse(pen, new Rectangle(pumpRect.Left + 20, pumpRect.Top + 10, 20, 20));
                g.DrawEllipse(pen, new Rectangle(pumpRect.Right - 40, pumpRect.Top + 10, 20, 20));
                g.DrawLine(pen, pumpRect.Left + 40, pumpRect.Top + 20, pumpRect.Right - 40, pumpRect.Top + 20);
                g.DrawLine(pen, pumpRect.Left + 30, pumpRect.Top + 10, pumpRect.Left + 30, pumpRect.Bottom - 10);
            }

            // 绘制泵名称
            using (Font font = new Font("微软雅黑", 9F, FontStyle.Bold))
            {
                using (Brush brush = new SolidBrush(Color.Black))
                {
                    SizeF textSize = g.MeasureString(pumpName, font);
                    g.DrawString(pumpName, font, brush, 
                        pumpRect.Left + (pumpRect.Width - textSize.Width) / 2, 
                        pumpRect.Bottom + 5);
                }
            }

            // 绘制状态指示器
            using (Font font = new Font("微软雅黑", 7F, FontStyle.Regular))
            {
                using (Brush brush = new SolidBrush(isRunning ? Color.Green : Color.Red))
                {
                    string statusText = isRunning ? "运行中" : "已停止";
                    SizeF textSize = g.MeasureString(statusText, font);
                    g.DrawString(statusText, font, brush, 
                        pumpRect.Left + (pumpRect.Width - textSize.Width) / 2, 
                        pumpRect.Top - 15);
                }
            }
        }
    }

    // 切换开关控件
    public class SwitchControl : Panel
    {
        private bool isOn = false;

        public bool IsOn
        {
            get { return isOn; }
            set 
            {
                isOn = value;
                this.Invalidate();
            }
        }

        public SwitchControl()
        {
            this.DoubleBuffered = true;
            this.ResizeRedraw = true;
            this.Size = new Size(40, 20);
            this.Click += new EventHandler(SwitchControl_Click);
        }

        void SwitchControl_Click(object sender, EventArgs e)
        {
            IsOn = !IsOn;
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            Graphics g = e.Graphics;
            g.SmoothingMode = SmoothingMode.AntiAlias;

            // 绘制开关背景
            using (Brush brush = new SolidBrush(isOn ? Color.Green : Color.Gray))
            {
                g.FillRectangle(brush, new Rectangle(0, 0, this.Width, this.Height));
            }
            using (Pen pen = new Pen(Color.Black, 1))
            {
                g.DrawRectangle(pen, new Rectangle(0, 0, this.Width - 1, this.Height - 1));
            }

            // 绘制开关滑块
            using (Brush brush = new SolidBrush(Color.White))
            {
                int x = isOn ? this.Width - 15 : 5;
                g.FillEllipse(brush, new Rectangle(x, 2, 16, 16));
            }
            using (Pen pen = new Pen(Color.Black, 1))
            {
                int x = isOn ? this.Width - 15 : 5;
                g.DrawEllipse(pen, new Rectangle(x, 2, 16, 16));
            }
        }
    }

    // 管道控件
    public class PipeControl : Panel
    {
        private bool isFlowOn = false;

        public bool IsFlowOn
        {
            get { return isFlowOn; }
            set 
            {
                isFlowOn = value;
                this.Invalidate();
            }
        }

        public PipeControl()
        {
            this.DoubleBuffered = true;
            this.ResizeRedraw = true;
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            Graphics g = e.Graphics;
            g.SmoothingMode = SmoothingMode.AntiAlias;

            // 绘制管道
            using (Pen pen = new Pen(Color.Gray, 3))
            {
                pen.DashStyle = DashStyle.Dash;
                g.DrawLine(pen, 0, this.Height / 2, this.Width, this.Height / 2);
            }

            // 绘制水流指示器
            if (isFlowOn)
            {
                using (Pen pen = new Pen(Color.Blue, 2))
                {
                    // 绘制流动箭头
                    for (int i = 20; i < this.Width - 10; i += 30)
                    {
                        DrawArrow(g, pen, new Point(i, this.Height / 2), new Point(i + 20, this.Height / 2));
                    }
                }
            }
        }

        private void DrawArrow(Graphics g, Pen pen, Point start, Point end)
        {
            g.DrawLine(pen, start, end);
            double angle = Math.Atan2(end.Y - start.Y, end.X - start.X);
            int arrowSize = 6;
            Point p1 = new Point(
                (int)(end.X - arrowSize * Math.Cos(angle - Math.PI / 6)),
                (int)(end.Y - arrowSize * Math.Sin(angle - Math.PI / 6))
            );
            Point p2 = new Point(
                (int)(end.X - arrowSize * Math.Cos(angle + Math.PI / 6)),
                (int)(end.Y - arrowSize * Math.Sin(angle + Math.PI / 6))
            );
            g.DrawLine(pen, end, p1);
            g.DrawLine(pen, end, p2);
        }
    }

    public partial class Form1 : Form
    {
        private bool isRunning = false;
        private double currentWaterLevel = 0.0;
        private double maxWaterLevel = 0.0;
        private double minWaterLevel = 0.0;
        private double voltage = 0.0;
        private double current = 0.0;
        private double frequency = 0.0;
        private double power = 0.0;
        private bool isPumpStarted = false; // 水泵启动状态
        private bool isVoltageAlarm = false; // 电压报警状态

        // 声明自定义控件
        private UPanel mainUPanel;
        private UPanel waterLevelUPanel;
        private UPanel powerUPanel;
        // 移除重复定义的statusLED
        private UInstrumentControl voltmeter;
        private AlarmControl alarmControl;
        private WaterTankControl storageTank;
        private WaterTankControl supplyTank;
        private WaterPumpControl waterPump;
        private PipeControl leftPipe;
        private PipeControl rightPipe;
        private PipeControl topPipe;

        // 添加字典用于存储ModBus参数名和控件的映射关系
        private Dictionary<string, ParamTextBox> modbusControlMap;

        List<StoreRegionlnfo> storeRegionlnfoList = null;
        List<ParaInfo> paraInfoList = null;
        Point point;//鼠标按下时点
        bool IsMoving = false;//标识是否拖动
        bool IsReading = false;//是否正在读

        /// <summary>
        /// 实时数据集合
        /// </summary>
        Dictionary<string, string> alaemSets = new Dictionary<string, string>();
        System.Timers.Timer myReadTimer= null;//读定时器
        System.Timers.Timer myLoadTimer= null;//加载定时器
        int IsStarted = 0;//是否喀什抽水
        bool IsLoadData = false;//是否初次采集完成
        SerialPort SerialPort= null;//串口对象
        IModbusSerialMaster rtuMaster= null;  //RTU通信


        public Form1()
        {
            InitializeComponent();
            // 设置按钮文本方向为垂直
            btnAuto.TextAlign = ContentAlignment.MiddleCenter;
            btnStop.TextAlign = ContentAlignment.MiddleCenter;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // 初始化参数设置
            InitParaSet();
            
            // 加载参数列表
            LoadParaList();
            
            // 加载存储区列表
            LoadStoreRegionList();
            
            // 初始化定时器
            InitTimers();
            
            try
            {
                // 创建ModBus RTU主站
                CreateRtuMaster();
                
                // 启动定时器
                if (myReadTimer != null)
                {
                    myReadTimer.Start();
                }
                if (myLoadTimer != null)
                {
                    myLoadTimer.Start();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("串口初始化失败：" + ex.Message);
            }
        }

        /// <summary>
        ///控件参数名设置
        /// </summary>
        private void InitParaSet()
        {
            // 初始化字典
            if (modbusControlMap == null)
            {
                modbusControlMap = new Dictionary<string, ParamTextBox>();
            }
            else
            {
                modbusControlMap.Clear();
            }
            
            // 创建功率信息控件
            //CreateParamTextBox("PumpPower", "功率", new Point(300, 100));
            //CreateParamTextBox("PumpFrequency", "频率", new Point(300, 135));
            //CreateParamTextBox("PumpEC", "电流", new Point(300, 170));
            //CreateParamTextBox("PumpVoltage", "电压", new Point(300, 205));
            
            //// 创建水位信息控件
            //CreateParamTextBox("CurrentWPosition", "当前水位", new Point(50, 100));
            //CreateParamTextBox("LowWPosition", "最低水位", new Point(50, 135));
            //CreateParamTextBox("HightWPosition", "最高水位", new Point(50, 170));
            
            //// 创建状态控件
            //CreateParamTextBox("DeviceStart", "设备状态", new Point(500, 100));
            //CreateParamTextBox("Pump01Start", "水泵状态", new Point(500, 135));
            //CreateParamTextBox("IsVoltageAlarm", "电压报警", new Point(500, 170));
        }

        // 辅助方法：创建参数文本框
        private void CreateParamTextBox(string varName, string title, Point location)
        {
            ParamTextBox textBox = new ParamTextBox();
            textBox.Title = title;
            textBox.Value = "0.00";
            textBox.Location = location;
            textBox.Size = new Size(120, 30);
            mainPanel.Controls.Add(textBox);
            
            // 添加到映射字典
            modbusControlMap[varName] = textBox;
        }
        


        private void InitAlarmSets()
        { 

        }

        private void InitTimers()
        {
            // 创建读取ModBus数据的定时器
            myReadTimer = new System.Timers.Timer();
            myReadTimer.Interval = 1000; // 1秒读取一次
            myReadTimer.Elapsed += MyReadTimer_Elapsed;
            myReadTimer.AutoReset = true;
            
            // 创建加载定时器
            myLoadTimer = new System.Timers.Timer();
            myLoadTimer.Interval = 5000; // 5秒加载一次
            myLoadTimer.Elapsed += MyLoadTimer_Elapsed;
            myLoadTimer.AutoReset = true;
        }

        private void MyReadTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (IsReading || SerialPort == null || !SerialPort.IsOpen)
            {
                return;
            }
            
            try
            {
                IsReading = true;
                // 读取ModBus数据并更新控件
                UpdateModbusData();
            }
            catch (Exception ex)
            {
                // 处理异常
            }
            finally
            {
                IsReading = false;
            }
        }

        private void MyLoadTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            // 加载数据逻辑
            if (!IsLoadData && SerialPort != null && SerialPort.IsOpen)
            {
                IsLoadData = true;
                // 可以在这里进行初始数据加载
            }
        }
        
       
        private void UpdateModbusData()
        {
            if (rtuMaster == null || paraInfoList == null)
            {
                return;
            }
            
            try
            {
                // 遍历所有参数信息
                foreach (ParaInfo para in paraInfoList)
                {
                    try
                    {
                        // 根据功能码读取不同类型的寄存器
                        if (para.DataType == "Bool")
                        {
                            // 读取线圈寄存器
                            bool[] values = rtuMaster.ReadCoils(para.SlaveId, para.Address, 1);
                            if (values != null && values.Length > 0)
                            {
                                // 处理布尔值
                                string displayValue = values[0] ? "开启" : "关闭";
                                // 更新对应的数据变量
                                if (para.ParaName == "DeviceStart")
                                {
                                    statusLabel.Text= displayValue;
                                }
                                else if (para.ParaName == "Pump01Start")
                                {
                                    isRunning = values[0];
                                }
                                
                                // 更新关联的控件
                                if (modbusControlMap != null && modbusControlMap.ContainsKey(para.ParaName))
                                {
                                    this.Invoke((MethodInvoker)delegate
                                    {
                                        modbusControlMap[para.ParaName].Value = displayValue;
                                    });
                                }
                            }
                        }
                        else
                        {
                            // 读取保持寄存器数据
                            int registerCount = para.DataType == "Float" ? 2 : 1;
                            ushort[] values = rtuMaster.ReadHoldingRegisters(para.SlaveId, para.Address, Convert.ToUInt16(registerCount));
                            if (values != null && values.Length >= registerCount)
                            {
                                // 根据数据类型处理数据
                                double value = 0;
                                if (para.DataType == "Int")
                                {
                                    value = values[0];
                                }
                                else if (para.DataType == "Float" && values.Length >= 2)
                                {
                                    // 正确处理浮点数（需要两个寄存器）
                                    byte[] bytes = new byte[4];
                                    BitConverter.GetBytes(values[0]).CopyTo(bytes, 0);
                                    BitConverter.GetBytes(values[1]).CopyTo(bytes, 2);
                                    value = BitConverter.ToSingle(bytes, 0);
                                }
                                
                                // 应用小数点位数
                                value = value / Math.Pow(10, para.DecimalCount);
                                
                                // 更新对应的数据变量
                                if (para.ParaName == "PumpPower")
                                {
                                    power = value;
                                }
                                else if (para.ParaName == "PumpEC")
                                {
                                    current = value;
                                }
                                else if (para.ParaName == "PumpFrequency")
                                {
                                    frequency = value;
                                }
                                else if (para.ParaName == "PumpVoltage")
                                {
                                    voltage = value;
                                    
                                    // 检查电压是否大于220V，更新报警状态
                                    bool newAlarmState = voltage > 220;
                                    if (newAlarmState != isVoltageAlarm)
                                    {
                                        isVoltageAlarm = newAlarmState;
                                        // 写入线圈寄存器，更新预警状态
                                        if (rtuMaster != null && SerialPort != null && SerialPort.IsOpen)
                                        {
                                            try
                                            {
                                                // 写入从机ID=3，地址=2的线圈寄存器
                                                rtuMaster.WriteSingleCoil(3, 2, isVoltageAlarm);
                                            }
                                            catch (Exception ex)
                                            {
                                                Console.WriteLine("写入电压报警状态失败: {0}", ex.Message);
                                            }
                                        }
                                    }
                                }
                                else if (para.ParaName == "CurrentWPosition")
                                {
                                    currentWaterLevel = value;
                                }
                                else if (para.ParaName == "LowWPosition")
                                {
                                    minWaterLevel = value;
                                }
                                else if (para.ParaName == "HightWPosition")
                                {
                                    maxWaterLevel = value;
                                }
                                
                                // 更新关联的控件
                                if (modbusControlMap != null && modbusControlMap.ContainsKey(para.ParaName))
                                {
                                    string unit = "";
                                    if (para.ParaName == "PumpPower") unit = "W";
                                    else if (para.ParaName == "PumpEC") unit = "A";
                                    else if (para.ParaName == "PumpFrequency") unit = "Hz";
                                    else if (para.ParaName == "PumpVoltage") unit = "V";
                                    else if (para.ParaName.Contains("WPosition")) unit = "m";
                                    
                                    string displayValue = string.Format("{0:F2} {1}", value, unit);
                                    
                                    // 在UI线程上更新控件
                                    this.Invoke((MethodInvoker)delegate
                                    {
                                        modbusControlMap[para.ParaName].Value = displayValue;
                                    });
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("读取参数 {0} 出错: {1}", para.ParaName, ex.Message);
                    }
                }

                // 水位控制逻辑
                if (rtuMaster != null && SerialPort != null && SerialPort.IsOpen)
                {
                    try
                    {
                        bool shouldPump = false;
                        
                        //if (isRunning) // 只有在系统运行时才进行水位控制
                        //{
                            if (currentWaterLevel <= minWaterLevel|| currentWaterLevel< maxWaterLevel)
                            {
                            isRunning = true;
                                // 当前水位低于或等于最低水位，需要开始抽水
                                shouldPump = true;
                                Console.WriteLine("开始抽水：当前水位({0}m) ≤ 最低水位({1}m)", currentWaterLevel, minWaterLevel);

                                // 模拟每次抽高加10（这里根据实际情况调整单位和增量）
                                double newWaterLevel = currentWaterLevel + 1.0;
                                if (newWaterLevel > maxWaterLevel)
                                {
                                    newWaterLevel = maxWaterLevel;
                                }

                                // 写入新的水位值到从机ID=2，地址=0的保持寄存器
                                ushort registerValue = (ushort)(newWaterLevel * Math.Pow(10, 2)); // 应用小数点位数
                                rtuMaster.WriteSingleRegister(2, 0, registerValue);
                                Console.WriteLine("更新水位：从{0}m增加到{1}m", currentWaterLevel, newWaterLevel);

                                // 立即更新本地变量以反映水位变化
                                currentWaterLevel = newWaterLevel;
                            }
                            else if (currentWaterLevel >= maxWaterLevel)
                            {

                                // 当前水位达到或超过最高水位，需要停止抽水
                                shouldPump = false;
                                isRunning = shouldPump;
                                 Console.WriteLine("停止抽水：当前水位({0}m) ≥ 最高水位({1}m)", currentWaterLevel, maxWaterLevel);
                            }
                        //}
                        //else
                        //{
                        //    // 系统不运行时，确保停止抽水
                        //    shouldPump = false;
                        //    Console.WriteLine("系统停止，停止抽水");
                        //}

                        // 写入线圈寄存器控制抽水状态
                        rtuMaster.WriteSingleCoil(3, 1, shouldPump);

 
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("控制抽水泵状态失败: {0}", ex.Message);
                    }
                }

                // 刷新界面以显示水位变化
                this.Invoke((MethodInvoker)delegate
                {
                    mainPanel.Refresh();
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine("ModBus通信错误: {0}", ex.Message);
            }
        }


        private void LoadParaList()
        {
            paraInfoList = new List<ParaInfo>()
            {
                new ParaInfo(){ParaName="PumpPower",SlaveId=1,Address=0,DataType="Int",DecimalCount=0},
                new ParaInfo(){ParaName="PumpEC",SlaveId=1,Address=1,DataType="Int",DecimalCount=0},
                new ParaInfo(){ParaName="PumpFrequency",SlaveId=1,Address=2,DataType="Int",DecimalCount=0},
                new ParaInfo(){ParaName="PumpVoltage",SlaveId=1,Address=3,DataType="Int",DecimalCount=0},
                new ParaInfo(){ParaName="CurrentWPosition",SlaveId=2,Address=0,DataType="Int",DecimalCount=2},
                new ParaInfo(){ParaName="LowWPosition",SlaveId=2,Address=1,DataType="Int",DecimalCount=2},
                new ParaInfo(){ParaName="HightWPosition",SlaveId=2,Address=2,DataType="Int",DecimalCount=2},
                new ParaInfo(){ParaName="DeviceStart",SlaveId=3,Address=0,DataType="Bool",DecimalCount=0},
                new ParaInfo(){ParaName="Pump01Start",SlaveId=3,Address=1,DataType="Bool",DecimalCount=0},
                new ParaInfo(){ParaName="IsVoltageAlarm",SlaveId=3,Address=2,DataType="Bool",DecimalCount=0},
                
            };
        }

        /// <summary>
        /// 存储区加载
        /// </summary>
        private void LoadStoreRegionList()
        {
            storeRegionlnfoList = new List<StoreRegionlnfo>()
            {
                new StoreRegionlnfo(){SlaveId=1,FunctionCode=3,StartAddress=0,Length=4},
                new StoreRegionlnfo(){SlaveId=2,FunctionCode=3,StartAddress=0,Length=3},
                new StoreRegionlnfo(){SlaveId=3,FunctionCode=1,StartAddress=0,Length=4}
            };
        }

        private void CreateRtuMaster()
        {
            try
            {
                // 关闭已打开的串口
                if (SerialPort != null && SerialPort.IsOpen)
                {
                    SerialPort.Close();
                }
                
                // 创建新的串口对象
                SerialPort = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
                SerialPort.ReadTimeout = 1000;  // 设置读取超时时间
                SerialPort.WriteTimeout = 1000; // 设置写入超时时间
                
                // 创建RTU主站
                rtuMaster = ModbusSerialMaster.CreateRtu(SerialPort);
                rtuMaster.Transport.ReadTimeout = 1000;
                
                // 打开串口
                SerialPort.Open();
                
                // 初始化加载状态
                IsLoadData = false;
                
                Console.WriteLine("ModBus RTU主站创建成功，串口已打开");
            }
            catch (Exception ex)
            {
                Console.WriteLine("创建ModBus RTU主站失败: {0}", ex.Message);
                throw;
            }
        }

        private void btnAuto_Click(object sender, EventArgs e)
        {
            // 启动系统
            UpdateStatus(true);
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            // 停止系统
            UpdateStatus(false);
        }

        private void mainPanel_Paint(object sender, PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            g.SmoothingMode = SmoothingMode.AntiAlias;

            // 创建渐变背景
            Rectangle clientRect = this.ClientRectangle;
            using (LinearGradientBrush brush = new LinearGradientBrush(
                clientRect, 
                Color.LightSkyBlue, 
                Color.SkyBlue, 
                LinearGradientMode.Vertical))
            {
                g.FillRectangle(brush, clientRect);
            }

            // 绘制水位信息
            DrawWaterLevelInfo(g);

            // 绘制功率信息
            DrawPowerInfo(g);

            // 绘制储水池
            DrawWaterStorageTank(g);

            // 绘制供水池
            DrawWaterSupplyTank(g);

            // 绘制管道连接
            DrawPipes(g);

            // 绘制抽水泵
            DrawWaterPump(g);

            // 绘制电压表
            DrawVoltmeter(g);
            
            

            // 绘制报警灯
            DrawAlarmLight(g);
        }

        private void statusLED_Paint(object sender, PaintEventArgs e)
        {
            // 绘制圆形LED指示灯
            Panel led = sender as Panel;
            using (Graphics g = e.Graphics)
            {
                g.SmoothingMode = SmoothingMode.AntiAlias;
                using (Brush brush = new SolidBrush(led.BackColor))
                {
                    g.FillEllipse(brush, new Rectangle(0, 0, led.Width - 1, led.Height - 1));
                }
                using (Pen pen = new Pen(Color.Black, 1))
                {
                    g.DrawEllipse(pen, new Rectangle(0, 0, led.Width - 1, led.Height - 1));
                }

                // 添加高光效果
                if (led.BackColor == Color.Green)
                {
                    using (Brush brush = new SolidBrush(Color.FromArgb(100, Color.White)))
                    {
                        g.FillEllipse(brush, new Rectangle(3, 3, led.Width - 6, led.Height - 6));
                    }
                }
            }
        }

        private void UpdateStatus(bool isStart)
        {
            // 更新运行状态
            isRunning = isStart;
            
            // 更新状态标签和LED颜色
            if (isStart)
            {
                pumpStatusLabel.Text = "运行中1";
                statusLED.BackColor = Color.Red;
                
                // 启动定时器读取数据
                if (myReadTimer != null && !myReadTimer.Enabled)
                {
                    myReadTimer.Start();
                }
            }
            else
            {
                pumpStatusLabel.Text = "已停止1";
                statusLED.BackColor = Color.Green;
                
                // 停止定时器
                if (myReadTimer != null && myReadTimer.Enabled)
                {
                    myReadTimer.Stop();
                }
                
              
            }
            
            // 重新绘制界面
            mainPanel.Refresh();
            statusLED.Refresh();
        }

        private void DrawWaterLevelInfo(Graphics g)
        {
            // 绘制圆角信息框
            Rectangle infoBox = new Rectangle(50, 50, 150, 80);
            GraphicsPath path = GetRoundRectangle(infoBox, 10);
            using (Brush brush = new SolidBrush(Color.White))
            {
                g.FillPath(brush, path);
            }
            using (Pen pen = new Pen(Color.Black, 1))
            {
                g.DrawPath(pen, path);
            }

            using (Font font = new Font("微软雅黑", 9F, FontStyle.Regular))
            {
                using (Brush brush = new SolidBrush(Color.Black))
                {
                    g.DrawString(string.Format("当前水位: {0:0.00} m", currentWaterLevel), font, brush, 60, 60);
                    g.DrawString(string.Format("最高水位: {0:0.00} m", maxWaterLevel), font, brush, 60, 85);
                    g.DrawString(string.Format("最低水位: {0:0.00} m", minWaterLevel), font, brush, 60, 110);
                }
            }
            // 绘制储水池标签
            using (Font font = new Font("微软雅黑", 9F, FontStyle.Bold))
            {
                using (Brush brush = new SolidBrush(Color.Black))
                {
                    g.DrawString("储水池", font, brush, 110, 140);
                }
            }
        }

        private void DrawPowerInfo(Graphics g)
        {
            // 绘制圆角功率信息框
            Rectangle powerBox = new Rectangle(300, 100, 150, 100);
            GraphicsPath path = GetRoundRectangle(powerBox, 10);
            using (Brush brush = new SolidBrush(Color.White))
            {
                g.FillPath(brush, path);
            }
            using (Pen pen = new Pen(Color.Black, 1))
            {
                g.DrawPath(pen, path);
            }

            using (Font font = new Font("微软雅黑", 9F, FontStyle.Regular))
            {
                using (Brush brush = new SolidBrush(Color.Black))
                {
                    g.DrawString(string.Format("功率: {0:0.00} W", power), font, brush, 310, 110);
                    g.DrawString(string.Format("频率: {0:0.00} Hz", frequency), font, brush, 310, 135);
                    g.DrawString(string.Format("电流: {0:0.00} A", current), font, brush, 310, 160);
                    g.DrawString(string.Format("电压: {0:0.00} V", voltage), font, brush, 310, 185);
                }
            }
        }

        private void DrawWaterStorageTank(Graphics g)
        {
            // 储水池位置和大小
            int x = 50;
            int y = 160;
            int width = 150;
            int height = 150;

            // 绘制池体
            using (Pen pen = new Pen(Color.Black, 2))
            {
                g.DrawRectangle(pen, x, y, width, height);
            }

            // 计算实际水位高度（基于当前水位、最低水位和最高水位）
            int waterHeight = 0;
            if (maxWaterLevel > minWaterLevel)
            {
                // 确保当前水位在有效范围内
                double validWaterLevel = Math.Max(minWaterLevel, Math.Min(currentWaterLevel, maxWaterLevel));
                // 计算相对水位比例（0-1）
                double waterRatio = (validWaterLevel - minWaterLevel) / (maxWaterLevel - minWaterLevel);
                // 转换为像素高度（留出一些边距）
                waterHeight = (int)(height * 0.9 * waterRatio);
            }
            else
            {
                // 如果最高水位和最低水位相等或无效，使用默认值
                waterHeight = isRunning ? (int)(height * 0.7) : (int)(height * 0.6);
            }

            // 绘制水（使用渐变填充）
            using (LinearGradientBrush brush = new LinearGradientBrush(
                new Point(x + 1, y + height - waterHeight),
                new Point(x + width - 1, y + height),
                Color.LightBlue, Color.Blue))
            {
                g.FillRectangle(brush, x + 1, y + height - waterHeight, width - 1, waterHeight);
            }
        }

       private void DrawWaterSupplyTank(Graphics g)
        {
            // 供水池位置和大小
            int x = 500;
            int y = 160;
            int width = 150;
            int height = 150;

            // 绘制池体
            using (Pen pen = new Pen(Color.Black, 2))
            {
                g.DrawRectangle(pen, x, y, width, height);
            }

            // 计算实际水位高度（基于当前水位、最低水位和最高水位）
            int waterHeight = 0;
            if (maxWaterLevel > minWaterLevel)
            {
                // 对于供水池，我们可以反向显示水位（抽水时增加）
                // 确保当前水位在有效范围内
                double validWaterLevel = Math.Max(minWaterLevel, Math.Min(currentWaterLevel, maxWaterLevel));
                // 计算相对水位比例（0-1）- 这里可以根据实际需求调整逻辑
                double waterRatio = 0.4 + (validWaterLevel - minWaterLevel) / (maxWaterLevel - minWaterLevel) * 0.3;
                // 转换为像素高度
                waterHeight = (int)(height * waterRatio);
            }
            else
            {
                // 如果最高水位和最低水位相等或无效，使用默认值
                waterHeight = isRunning ? (int)(height * 0.5) : (int)(height * 0.4);
            }

            // 绘制水（使用渐变填充）
            using (LinearGradientBrush brush = new LinearGradientBrush(
                new Point(x + 1, y + height - waterHeight),
                new Point(x + width - 1, y + height),
                Color.LightBlue, Color.Blue))
            {
                g.FillRectangle(brush, x + 1, y + height - waterHeight, width - 1, waterHeight);
            }
        }

        private void DrawPipes(Graphics g)
        {
            using (Pen pen = new Pen(Color.Black, 2))
            {
                pen.DashStyle = DashStyle.Dash;
                // 左管道
                g.DrawLine(pen, 200, 235, 300, 235);
                // 右管道
                g.DrawLine(pen, 450, 235, 500, 235);
                // 上管道
                g.DrawLine(pen, 375, 100, 500, 100);
            }

            // 绘制水流方向箭头
            if (isRunning)
            {
                using (Pen pen = new Pen(Color.Blue, 2))
                {
                    // 左管道水流方向
                    DrawArrow(g, pen, new Point(230, 235), new Point(270, 235));
                    // 右管道水流方向
                    DrawArrow(g, pen, new Point(470, 235), new Point(490, 235));
                    // 上管道水流方向
                    DrawArrow(g, pen, new Point(450, 100), new Point(480, 100));
                }
            }
        }

        private void DrawWaterPump(Graphics g)
        {
            // 绘制泵体矩形
            Rectangle pumpBody = new Rectangle(300, 235, 150, 50);
            using (Brush brush = new SolidBrush(Color.LightGray))
            {
                g.FillRectangle(brush, pumpBody);
            }
            using (Pen pen = new Pen(Color.Black, 1))
            {
                g.DrawRectangle(pen, pumpBody);
            }
            
            // 绘制水泵标签
            using (Font font = new Font("微软雅黑", 9F, FontStyle.Bold))
            {
                using (Brush brush = new SolidBrush(Color.Black))
                {
                    g.DrawString("抽水泵", font, brush, 340, 250);
                    
                    // 显示水泵运行状态
                    string statusText = isRunning ? "运行中" : "已停止";
                    Color statusColor = isRunning ? Color.Green : Color.Red;
                    using (Brush statusBrush = new SolidBrush(statusColor))
                    {
                        g.DrawString(statusText, font, statusBrush, 340, 270);
                    }
                }
            }
        }

        private void DrawVoltmeter(Graphics g)
        {
            int centerX = 375;
            int centerY = 60;
            int radius = 30;

            // 绘制表盘背景（使用渐变）
            using (LinearGradientBrush brush = new LinearGradientBrush(
                new Point(centerX - radius, centerY - radius),
                new Point(centerX + radius, centerY + radius),
                Color.LightGray, Color.White))
            {
                g.FillEllipse(brush, centerX - radius, centerY - radius, radius * 2, radius * 2);
            }

            // 绘制表盘
            using (Pen pen = new Pen(Color.Black, 1))
            {
                g.DrawEllipse(pen, centerX - radius, centerY - radius, radius * 2, radius * 2);
            }

            // 绘制刻度
            using (Pen pen = new Pen(Color.Black, 1))
            {
                for (int i = 0; i <= 12; i++)
                {
                    double angle = Math.PI * 1.5 - (Math.PI * 1.2) * i / 12;
                    int x1 = centerX + (int)(Math.Cos(angle) * radius * 0.8);
                    int y1 = centerY - (int)(Math.Sin(angle) * radius * 0.8);
                    int x2 = centerX + (int)(Math.Cos(angle) * radius);
                    int y2 = centerY - (int)(Math.Sin(angle) * radius);
                    g.DrawLine(pen, x1, y1, x2, y2);
                }
            }

            // 绘制刻度值
            using (Font font = new Font("Arial", 5F, FontStyle.Regular))
            {
                using (Brush brush = new SolidBrush(Color.Black))
                {
                    string[] values = { "0", "30", "60", "90", "120", "150", "180", "210", "240", "270", "300" };
                    for (int i = 0; i < values.Length; i++)
                    {
                        double angle = Math.PI * 1.5 - (Math.PI * 1.2) * i / 10;
                        int x = centerX + (int)(Math.Cos(angle) * radius * 1.2);
                        int y = centerY - (int)(Math.Sin(angle) * radius * 1.2);
                        SizeF size = g.MeasureString(values[i], font);
                        g.DrawString(values[i], font, brush, x - size.Width / 2, y - size.Height / 2);
                    }
                }
            }

            // 绘制电压标签
            using (Font font = new Font("微软雅黑", 8F, FontStyle.Bold))
            {
                using (Brush brush = new SolidBrush(Color.Blue))
                {
                    g.DrawString("电压", font, brush, centerX - 10, centerY - 45);
                }
            }

            // 绘制指针
            using (Pen pen = new Pen(Color.Red, 1))
            {
                double voltageRatio = voltage / 300.0;
                double angle = Math.PI * 1.5 - (Math.PI * 1.2) * voltageRatio;
                int x = centerX + (int)(Math.Cos(angle) * radius * 0.6);
                int y = centerY - (int)(Math.Sin(angle) * radius * 0.6);
                g.DrawLine(pen, centerX, centerY, x, y);
            }

            // 绘制中心点
            using (Brush brush = new SolidBrush(Color.Black))
            {
                g.FillEllipse(brush, centerX - 2, centerY - 2, 4, 4);
            }
        }

        private void DrawAlarmLight(Graphics g)
        {
            int x = 500;
            int y = 120;
            int size = 30;

            // 绘制底座
            using (Brush brush = new SolidBrush(Color.Gray))
            {
                g.FillRectangle(brush, new Rectangle(x + 5, y + 20, 20, 10));
            }

            // 绘制报警灯 - 使用isVoltageAlarm变量控制颜色
            if (isVoltageAlarm)
            {
                // 报警状态（显示红色）
                using (Brush brush = new SolidBrush(Color.Red))
                {
                    g.FillEllipse(brush, new Rectangle(x, y, size, 25));
                }
                // 高光
                using (Brush brush = new SolidBrush(Color.FromArgb(100, Color.White)))
                {
                    g.FillEllipse(brush, new Rectangle(x + 2, y + 2, 15, 12));
                }
            }
            else
            {
                using (Brush brush = new SolidBrush(Color.Gray))
                {
                    g.FillEllipse(brush, new Rectangle(x, y, size, 25));
                }
            }
            using (Pen pen = new Pen(Color.Black, 1))
            {
                g.DrawEllipse(pen, new Rectangle(x, y, size, 25));
            }
        }

        private void DrawArrow(Graphics g, Pen pen, Point start, Point end)
        {
            g.DrawLine(pen, start, end);
            double angle = Math.Atan2(end.Y - start.Y, end.X - start.X);
            int arrowSize = 6;
            Point p1 = new Point(
                (int)(end.X - arrowSize * Math.Cos(angle - Math.PI / 6)),
                (int)(end.Y - arrowSize * Math.Sin(angle - Math.PI / 6))
            );
            Point p2 = new Point(
                (int)(end.X - arrowSize * Math.Cos(angle + Math.PI / 6)),
                (int)(end.Y - arrowSize * Math.Sin(angle + Math.PI / 6))
            );
            g.DrawLine(pen, end, p1);
            g.DrawLine(pen, end, p2);
        }

        private GraphicsPath GetRoundRectangle(Rectangle rect, int radius)
        {
            GraphicsPath path = new GraphicsPath();
            int diameter = radius * 2;

            // 左上圆角
            path.AddArc(rect.X, rect.Y, diameter, diameter, 180, 90);
            // 右上圆角
            path.AddArc(rect.Right - diameter, rect.Y, diameter, diameter, 270, 90);
            // 右下圆角
            path.AddArc(rect.Right - diameter, rect.Bottom - diameter, diameter, diameter, 0, 90);
            // 左下圆角
            path.AddArc(rect.X, rect.Bottom - diameter, diameter, diameter, 90, 90);
            path.CloseFigure();

            return path;
        }
        // ... existing code ...
    }
}


